using System;
using System.Text;

namespace LiJ.Common.Core.Utils
{
	/// <summary>
	/// 字符串通用功能
	/// </summary>
	public static class StringUtil
	{
		private static readonly Random Rnd = new Random(DateTime.Now.Millisecond);

		private static readonly char[] ArrChar = new char[60]
		{
			'0',
			'1',
			'2',
			'3',
			'4',
			'5',
			'6',
			'7',
			'8',
			'9',
			'a',
			'b',
			'd',
			'c',
			'e',
			'f',
			'g',
			'h',
			'i',
			'j',
			'k',
			'l',
			'm',
			'n',
			'p',
			'r',
			'q',
			's',
			't',
			'u',
			'v',
			'w',
			'z',
			'y',
			'x',
			'A',
			'B',
			'C',
			'D',
			'E',
			'F',
			'G',
			'H',
			'I',
			'J',
			'K',
			'L',
			'M',
			'N',
			'Q',
			'P',
			'R',
			'T',
			'S',
			'V',
			'U',
			'W',
			'X',
			'Y',
			'Z'
		};

		private const string ArrCodeStr = "12356789ABCDEFGHJKLMNPQRSTUVWXYZ";

		/// <summary>
		/// 生成随机串
		/// </summary>
		/// <returns></returns>
		public static string RandomStr(int length = 8)
		{
			StringBuilder stringBuilder = new StringBuilder(length);
			for (int i = 0; i < length; i++)
			{
				stringBuilder.Append(ArrChar[Rnd.Next(0, 59)]);
			}
			return stringBuilder.ToString();
		}

		/// <summary>
		/// 数字转化为短码
		/// </summary>
		/// <param name="num"></param>
		/// <returns></returns>
		public static string ToCode(this long num)
		{
			StringBuilder stringBuilder = new StringBuilder(13);
			while (num > 0)
			{
				long num2 = num & 0x1F;
				stringBuilder.Append("12356789ABCDEFGHJKLMNPQRSTUVWXYZ"[(int)num2]);
				num >>= 5;
			}
			return stringBuilder.ToString();
		}

		/// <summary>
		/// 根据短码反推数字
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public static long ToCodeNum(this string code)
		{
			if (string.IsNullOrEmpty(code))
			{
				return 0L;
			}
			int length = code.Length;
			if (length > 13)
			{
				throw new ArgumentOutOfRangeException("code", "the code is not from [ToCode] method !");
			}
			long num = 0L;
			for (int num2 = length - 1; num2 >= 0; num2--)
			{
				int num3 = "12356789ABCDEFGHJKLMNPQRSTUVWXYZ".IndexOf(code[num2]);
				if (num3 < 0)
				{
					throw new ArgumentOutOfRangeException("code", "the code is not from [ToCode] method !");
				}
				num = (num << 5 ^ num3);
			}
			return num;
		}
	}
}
